package com.xc.xcmanage.domain.dto;

import com.alibaba.fastjson.annotation.JSONField;
import com.xc.xcmanage.domain.pojo.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


public class LoginUser implements UserDetails {

    private SysUser sysUser;

    private List<String> perms;

    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    public LoginUser() {
    }

    public LoginUser(SysUser sysUser,List<String> perms) {
        this.sysUser = sysUser;
        this.perms = perms;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        if(authorities != null){
            return authorities;
        }

        authorities = new ArrayList<>();

        perms.forEach(perm ->{
            if (StringUtils.hasText(perm)){
                authorities.add(new SimpleGrantedAuthority(perm));
            }
        });


        return authorities;
    }

    public SysUser getSysUser() {
        return sysUser;
    }

    public List<String> getPerms() {
        return perms;
    }

    public void setSysUser(SysUser sysUser) {
        this.sysUser = sysUser;
    }

    public void setPerms(List<String> perms) {
        this.perms = perms;
    }

    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return sysUser.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
